<template>
  <div class="el-table-toolbar" :class="mode=='inner'?'inner-table-toolbar':''">
    <el-row>
      <el-col class="el-table-toolbar-left" :span="24-rightToolbarSpan">
        <div class="table-toolbar-left-slot">
          <slot name="toolbarLeft-slotLeft" />
          <el-radio-group v-model="navLabel" size="small">
            <el-radio-button v-for="(rt, key) in brotherRoutes" :key="key" :label="rt.meta.title" @click.native="gotoListpage(rt)">
              {{ rt.meta.title }}
              <span v-if="tabCount!==null&&tabCount[rt.meta.code]!==undefined&&tabCount[rt.meta.code]!==null&&tabCount[rt.meta.code]!==''">({{ tabCount[rt.meta.code] }})</span>
            </el-radio-button>
            <el-radio-button v-for="(btn, btnKey) in customToolbarBtns" :key="btnKey" :label="btn.name" @click.native="gotoListpage(btn)" />
          </el-radio-group>
          <slot name="toolbarLeft-slotRight" />
        </div>
      </el-col>
      <el-col v-if="tbColumns.length>0" class="el-table-toolbar-right" :span="rightToolbarSpan">
        <el-popover
          v-model="selColumnVisible"
          placement="bottom-start"
          :visible-arrow="false"
          width="150"
          trigger="manual"
        >
          <el-checkbox-group v-model="enabledColums" @change="setColumnEnabled">
            <template v-for="(column, key) in tbColumns">
              <el-checkbox v-if="column.title!==undefined" :key="key" :label="column.field">{{ column.title }}</el-checkbox>
            </template>
          </el-checkbox-group>

          <el-button-group slot="reference" class="toolbar-button-group">
            <el-button plain size="small" icon="el-icon-refresh" title="刷新" class="refresh_btn" @click="refreshListData" />
            <el-button plain size="small" icon="el-icon-s-grid" title="列" class="column_btn" @click.stop="selColumnVisible = !selColumnVisible">
              <i class="el-icon-caret-bottom" />
            </el-button>
            <template v-for="(btn, btnKey) in toolbarRightBtns">
              <el-button v-if="btn.btnType==='toolbar'" :key="btnKey" :class="(btn.btnIcon ? btn.btnIcon.split('.')[0] : ( btn.id || btn.btnPermission))+'_btn'" plain size="small" @click="btnClick(btn)">
                <svg-icon v-if="btn.btnIcon.indexOf('.svg')!==-1" class="svg_icon" :icon-class="btn.btnIcon.substring(0,btn.btnIcon.indexOf('.svg'))" />
                <i v-if="btn.btnIcon.indexOf('.svg')===-1" :class="'el-icon-'+btn.btnIcon+' '+'el_icon'" /><span>{{ btn.btnName }}</span>
              </el-button>
              <el-button v-if="btn.btnType==='toolbarBtnGroup'" :key="btnKey" :class="btn.id+'_'+btnKey" plain size="small" @click.stop="groupTooBarBtn(btn,btnKey)">
                <svg-icon v-if="btn.btnIcon.indexOf('.svg')!==-1" :icon-class="btn.btnIcon.substring(0,btn.btnIcon.indexOf('.svg'))" />
                <i v-if="btn.btnIcon.indexOf('.svg')===-1" :class="'el-icon-'+btn.btnIcon" />
                <span>{{ btn.btnName }}</span>
                <i :class="'el-icon-caret-'+(tipPopper?'top':'bottom')" />
              </el-button>
            </template>
          </el-button-group>
        </el-popover>
        <div v-show="tipPopper" id="el-popover-4751" role="tooltip" aria-hidden="false" class="el-popover el-popper tip_popper" tabindex="0">
          <template v-for="(link,index) in toobarChildren">
            <div :key="index" class="tip_popper_btn">
              <el-link :underline="false" class="tip_popper_link" @click="btnClick(link)">
                <svg-icon v-if="link.btnIcon.indexOf('.svg')!==-1" :icon-class="link.btnIcon.substring(0,link.btnIcon.indexOf('.svg'))" />
                <i v-if="link.btnIcon&&link.btnIcon.indexOf('.svg')===-1" :class="'el-icon-'+link.btnIcon" />
                <span>{{ link.btnName }}</span>
              </el-link>
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { generateTitle } from '@/global/utils/i18n'

export default {
    name: 'Toolbar',
    props: {
        toolbarBtns: { type: Array, default: function() { return [] } },
        rightToolbarSpan: { type: Number, default: function() { return 12 } }, // 右上操作按钮组列格栅数，共24列
        customToolbarBtns: { type: Array, default: function() { return [] } },
        tbColumns: { type: Array, default: function() { return [] } },
        mode: { type: String, default: 'listpage' }, // 列表呈现模式：listpage=普通列表，inner=表单内嵌子表
        setColumnEnabled: { type: Function, default: function() {} },
        selectCustomToolbar: { type: Function, default: function() { return true } },
        moduleInfo: { type: Object, default: null }
    },
    data() {
        return {
            navLabel: '',
            brotherRoutes: [],
            selColumnVisible: false,
            enabledColums: [],
            toobarChildren: [],
            tipPopper: false,
            lastgroupbtnID: '',
            tabCount: null
        }
    },
    computed: {
        routes() {
            return this.$store.getters.routes
        },
        toolbarRightBtns() {
            const groupToobarChild = this.toolbarBtns.filter(item => {
                if (typeof item.btnPermission !== 'string') {
                    item.btnI18nCode = item.btnI18nCode || (item.btnIcon || item.btnName).replace('Ids', '').replace('Object', '')
                } else {
                    item.btnI18nCode = item.btnI18nCode || (item.btnPermission || item.btnIcon || item.btnName).replace('Ids', '').replace('Object', '')
                }

                item.btnName = generateTitle(item, this)

                if (item.btnType === 'toolbarChildBtn' && item.btnPermission) return true
            })

            const toobars = this.toolbarBtns.filter(item => {
                if (item.btnType === 'toolbar' && item.btnPermission) {
                    return true
                } else if (item.btnType === 'toolbarBtnGroup' && item.btnPermission) {
                    item.children = groupToobarChild
                    return true
                }
            })
            return toobars
        }
    },
    watch: {

    },
    created() {
        this.navLabel = ''
        this.brotherRoutes = []

        if (((this.$route.meta.level === 4 && this.$route.meta.parentTarget !== 'leftMenuItem') || this.$route.meta.parentTarget === 'rightLabel') && this.$route.query.pageType !== 'child') {
            this.brotherRoutes = this.findBrotherRoutes(this.routes, this.$route.meta.parentId)
            if (this.brotherRoutes.length > 0) {
                this.brotherRoutes.forEach(item => {
                    item.meta.title = generateTitle(item.meta, this)
                })
                this.navLabel = this.brotherRoutes[0].meta.title
                for (const rt of this.brotherRoutes) {
                    if (this.$route.meta.id === rt.meta.id) {
                        this.navLabel = rt.meta.title
                        break
                    }
                }
            }
        }
        if (this.customToolbarBtns !== null) {
            if (this.customToolbarBtns.length > 0) {
                const defaultLabel = this.customToolbarBtns.filter(item => item.isDefault)
                this.navLabel = defaultLabel.length > 0 ? defaultLabel[0].name : this.customToolbarBtns[0].name
            }
        }

        this.tbColumns.forEach(column => {
            if (column.enabled === true) {
                this.enabledColums.push(column.field)
            }
        })

        this.$bus.on('bodyOnClick', this.bodyOnClick)
        this.$bus.on('setTabFileCount', this.setTabFileCount)
    },
    beforeDestroy() {
        this.$bus.off('bodyOnClick', this.bodyOnClick)
        this.$bus.off('setTabFileCount', this.setTabFileCount)
        document.removeEventListener('click', this.windowClick, false)
    },
    mounted() {
        document.addEventListener('click', this.windowClick, false)
        this.setTabFileCount()
    },
    methods: {
        setTabFileCount() {
            if (this.moduleInfo !== null && this.moduleInfo.queryCountUrl !== undefined && this.moduleInfo.queryCountUrl != null && this.moduleInfo.queryCountUrl !== '') {
                const urls = this.moduleInfo.queryCountUrl.split(',')
                urls.forEach(url => {
                    this.$http({
                        method: 'GET',
                        url: url
                    }).then(res => {
                        if (res.code === 'success') {
                            this.tabCount = this.tabCount || {}
                            for (const key in res.body.count) {
                                this.tabCount[key] = res.body.count[key]
                            }
                            this.$forceUpdate()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                })
            }
        },
        windowClick() {
            this.tipPopper = false
        },
        findBrotherRoutes(routes, parentId) {
            let brothers = []
            for (const router of routes) {
                if (router.meta.id === parentId) {
                    brothers = router.children
                } else if (router.children && router.children.length > 0) {
                    brothers = this.findBrotherRoutes(router.children, parentId)
                }

                if (brothers.length > 0) break
            }
            return brothers
        },
        bodyOnClick() {
            this.selColumnVisible = false
        },
        refreshListData() {
            this.$parent.refreshListData()
        },
        gotoListpage(to) {
            if (to.type && to.type === 'custom_btn') {
                if (typeof this.selectCustomToolbar === 'function') {
                    this.selectCustomToolbar(to)
                }
            } else {
                this.$router.push({
                    path: to.path
                })
            }
        },
        btnClick(btn) {
            if (btn.btnParams !== null && btn.btnParams !== undefined) {
                btn.btnClick.apply(this.$parent, btn.btnParams)
            } else if (btn.clickType && btn.clickType === 'custom_toolbar_click') {
                btn.btnClick.apply(this.$parent, [btn])
            } else {
                btn.btnClick.apply(this.$parent)
            }
        },
        groupTooBarBtn(btn, index) {
            const col = document.querySelector('.el-table-toolbar-right')
            const btnDOM = document.querySelector('.' + btn.id + '_' + index)
            const childBtnDOM = document.querySelector('.tip_popper')
            const left = col.offsetWidth - btnDOM.offsetLeft - btnDOM.offsetWidth + 'px'
            this.toobarChildren = btn.children
            childBtnDOM.style.right = left
            if (this.lastgroupbtnID === btn.id + '_' + index) {
                this.tipPopper = !this.tipPopper
            } else {
                this.tipPopper = true
            }
            this.lastgroupbtnID = btn.id + '_' + index
        }
    }
}
</script>

<style lang="scss" scoped>
    .el-table-toolbar{
        margin: 0 0 10px 0;
        .el-row{
            height: 32px;
            line-height: 32px;
        }
        .el-table-toolbar-left{
            height: 100%;
            .table-toolbar-left-slot{
                display: flex;
            }
        }
    }
    .inner-table-toolbar{
        margin-top:6px;
        margin-right:6px;
    }
    .el-table-toolbar-right{
        text-align: right;
        position: relative;
    }
    .el-checkbox-group{
        line-height: 25px;
    }
    /deep/ .el-checkbox__input.is-checked + .el-checkbox__label{
            color: inherit;
    }
    .tip_popper{
        min-width: 100px;
        text-align: center;
        position: absolute;
        top: 40px;
        right: 0;
        transform-origin: center top;
        z-index: 2001;
        padding: 0;
        .tip_popper_btn{
            line-height: 30px;
            padding: 6px 0;
            .tip_popper_link{
                font-size: 14px!important;
                width: 100%;
                padding: 0 17px;
            }
            .tip_popper_link:hover{
                background: #f5f7fa;
                color: #66b1ff;
            }
        }
        .tip_popper_btn:not(:last-child){border-bottom: 1px solid #EBEEF5;}
    }
</style>
